package com.aidex.biz.service.impl;

import com.aidex.biz.domain.*;
import com.aidex.biz.domain.vo.CustomerVo;
import com.aidex.biz.mapper.CustomerMapper;
import com.aidex.biz.mapper.TempShareMapper;
import com.aidex.biz.service.*;
import com.aidex.common.annotation.DataScope;
import com.aidex.common.core.domain.entity.Company;
import com.aidex.common.core.domain.entity.SysUser;
import com.aidex.common.core.service.BaseServiceImpl;
import com.aidex.common.exception.CustomException;
import com.aidex.common.utils.HardwareID;
import com.aidex.common.utils.NumberUtils;
import com.aidex.common.utils.SecurityUtils;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.sms.ChuangLanSmsClient;
import com.aidex.common.utils.sms.JdSmsClient;
import com.aidex.framework.cache.DictUtils;
import com.aidex.system.domain.SysDictData;
import com.aidex.system.mapper.SysUserMapper;
import com.aidex.system.service.CompanyService;
import com.aidex.system.service.ISysUserService;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.jdcloud.sdk.service.sms.model.BatchSendResponse;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.logging.Level;

/**
 * 左心房客户推送信息Service业务层处理
 *
 * @author sean
 * @email 2074844820@qq.com
 * @date 2023-04-03
 */
@Service
@Transactional(readOnly = true)
public class CustomerServiceImpl extends BaseServiceImpl<CustomerMapper, Customer> implements CustomerService {
    private static final Logger log = LoggerFactory.getLogger(CustomerServiceImpl.class);
    final String secretKey = "11662107190";

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private TempShareService tempShareService;

    @Autowired
    private TempShareMapper tempShareMapper;
    @Autowired
    private ShareLogService shareLogService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private AccountLogService accountLogService;
    @Autowired
    private SmsLogService smsLogService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysUserService iSysUserService;

    /**
     * 获取单条数据
     *
     * @param customer 左心房客户推送信息
     * @return 左心房客户推送信息
     */
    @Override
    public Customer get(Customer customer) {
        Customer dto = super.get(customer);
        return dto;
    }

    /**
     * 获取单条数据
     *
     * @param id 左心房客户推送信息id
     * @return 左心房客户推送信息
     */
    @Override
    public Customer get(String id) {
        Customer dto = super.get(id);
        return dto;
    }


    /**
     * 查询左心房客户推送信息列表
     *
     * @param customer 左心房客户推送信息
     * @return 左心房客户推送信息
     */
    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public List<Customer> findList(Customer customer) {
        return super.findList(customer);
    }

    /**
     * 分页查询左心房客户推送信息列表
     *
     * @param customer 左心房客户推送信息
     * @return 左心房客户推送信息
     */
    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public PageInfo<Customer> findPage(Customer customer) {
        return super.findPage(customer);
    }

    /**
     * 保存左心房客户推送信息
     *
     * @param customer
     * @return 结果
     */
    @Override
    public boolean save(Customer customer) {
        return super.save(customer);
    }


    /**
     * 删除左心房客户推送信息信息
     *
     * @param customer
     * @return 结果
     */
    @Override
    public boolean remove(Customer customer) {
        return super.remove(customer);
    }

    /**
     * 批量删除左心房客户推送信息
     *
     * @param ids 需要删除的左心房客户推送信息ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deleteCustomerByIds(String[] ids) {
        return mapper.deleteCustomerByIds(ids);
    }

    /**
     * 获取最大编号
     *
     * @param customer 左心房客户推送信息
     * @return 结果
     */
    @Override
    public int findMaxSort(Customer customer) {
        return NumberUtils.nextOrder(mapper.findMaxSort(customer));
    }

    @Override
    public boolean findCustomerByphone(String phone,String type) {
        Customer customer = new Customer();
        customer.setPhone(phone);
        customer.setType(type);
        return mapper.findList(customer).size() > 0;
    }

    @Transactional(readOnly = false)
    @Override
    public Map savePushCustomer(CustomerVo customer) {

        Map maps = new HashMap();
        try {

            StringBuffer stringBuffer = new StringBuffer();
            String remarkss = "";
            if (customer.getRemark() != "" && customer.getRemark() != null) {
                remarkss = customer.getRemark().replaceAll("\\\\n", "YY");
            }
            if (customer.getAge() != null) {
                stringBuffer.append("age=" + customer.getAge());
                if (customer.getClueId() != null) {
                    stringBuffer.append("&clueId=" + customer.getClueId());
                }
            } else {
                if (customer.getClueId() != null) {
                    stringBuffer.append("clueId=" + customer.getClueId());
                }
            }
            if (customer.getCreateTime() != null) {
                stringBuffer.append("&createTime=" + customer.getCreateTime());
            }
            if (customer.getCusSourceNum() != "" && customer.getCusSourceNum() != null) {
                stringBuffer.append("&cusSourceNum=" + customer.getCusSourceNum());
            }
            if (customer.getCusSourceType() != "" && customer.getCusSourceType() != null) {
                stringBuffer.append("&cusSourceType=" + customer.getCusSourceType());
            }
            if (customer.getCusTypeStr() != "" && customer.getCusTypeStr() != null) {
                stringBuffer.append("&cusTypeStr=" + customer.getCusTypeStr());
            }
            if (customer.getCustomerLocation() != "" && customer.getCustomerLocation() != null && customer.getCustomerLocation() != "未知") {
                stringBuffer.append("&customerLocation=" + customer.getCustomerLocation());
            }
            if (customer.getIp() != "" && customer.getIp() != null) {
                stringBuffer.append("&ip=" + customer.getIp());
            }
            if (customer.getLoanAmount() != "" && customer.getLoanAmount() != null) {
                stringBuffer.append("&loanAmount=" + customer.getLoanAmount());
            }
            if (customer.getLocation() != "" && customer.getLocation() != null && customer.getLocation() != "未知") {
                stringBuffer.append("&location=" + customer.getLocation());
            }
            if (customer.getMobile() != "" && customer.getMobile() != null) {
                stringBuffer.append("&mobile=" + customer.getMobile());
            }
            if (customer.getName() != "" && customer.getName() != null) {
                stringBuffer.append("&name=" + customer.getName());
            }
            if (customer.getRemark() != "" && customer.getRemark() != null) {
                String[] remarks = remarkss.split("YY");
                String strm = "";
                for (int i = 0; i < remarks.length; i++) {
                    if (i == remarks.length - 1) {
                        strm += remarks[i];
                    } else {
                        strm += remarks[i] + "\n";
                    }

                }
                stringBuffer.append("&remark=" + strm);
            }
            if (customer.getSex() != "" && customer.getSex() != null) {
                stringBuffer.append("&sex=" + customer.getSex());
            }
            if (customer.getTextData() != "" && customer.getTextData() != null) {
                stringBuffer.append("&textData=" + customer.getTextData());
            }
            if (customer.getTimestamp() != null) {
                stringBuffer.append("&timestamp=" + customer.getTimestamp());
            }
            if (customer.getUrl() != "" && customer.getUrl() != null) {
                stringBuffer.append("&url=" + customer.getUrl());
            }
            String sgin1 = DigestUtils.md5Hex(stringBuffer.toString() + secretKey);
            if (sgin1.equals(customer.getSign())) {



                Customer dk = new Customer();
                //19车抵 20房抵 22信贷23公积金贷
                if (customer.getCusTypeStr().equals("车抵")) {
                    dk.setType("1");
                }
                if (customer.getCusTypeStr().equals("房抵")) {
                    dk.setType("2");
                }
                if (customer.getCusTypeStr().equals("信贷")) {
                    dk.setType("3");
                }
                if (customer.getCusTypeStr().equals("公积金")) {
                    dk.setType("4");
                }
                dk.setCityName(customer.getCustomerLocation());
                dk.setPhone(customer.getMobile());
                dk.setRemark(customer.getRemark());
                dk.setAmount(customer.getLoanAmount());
                dk.setCusName(customer.getName());
                dk.setClueId(String.valueOf(customer.getClueId()));
                dk.setIp(customer.getIp());
                dk.setReceiveTime(new Date(customer.getCreateTime()));
                dk.setIsDail(0l);
                //判断是否重名
                Boolean res = findCustomerByphone(dk.getPhone(),dk.getType());
                if(res){
                    //相同业务相同手机号码标记为重复客户
                    dk.setStatus("-88");
                }else{
                    dk.setStatus("0");
                }

                save(dk);
                maps.put("code", "200");
                maps.put("message", "推送成功");
                maps.put("data", "success");

            } else {
                maps.put("code", "400");
                maps.put("message", "验签失败！");
                maps.put("data",
                        "组合原字符串:" + stringBuffer + "=============系统组装的签名:" + sgin1 + "=============传输的签名:" + customer.getSign());
            }
        } catch (Exception exception) {
            log.error("调用ApiPushCustomerController.savePushCustomer",JSONObject.toJSONString(customer));
            maps.put("code","500");
            maps.put("message",exception.getMessage());
            maps.put("data",JSONObject.toJSONString(customer));

        }
        return maps;
    }

    /**
     * 分配客户给用户
     *
     * @param customer
     */
    @Transactional(readOnly = false)
    @Override
    public void shareCustomer(Customer customer) {
        // 根据客户信息查询对应的用户
        SysUser user = findNextShareUser(customer);
        // 如果有分配的用户
        if (null != user) {
            try {
                //  获取公司信息
                Company company = companyService.get(user.getCompanyId());
                // TODO  判断用户类型，如果是系统账号进行分配，如果不是系统账户则调用API推送信息
                if ("2".equals(user.getBusType())) {

                }
                //开始分配
                customer = mapper.get(customer.getId());
                customer.setUserId(user.getUserId());
                customer.setUserName(user.getName());
                customer.setDeptId(user.getDeptId());
                customer.setDeptName(user.getDeptName());
                customer.setCompanyId(user.getCompanyId());
                customer.setShareDate(new Date());
                // 添加临时分配记录
                TempShare tempShare = new TempShare();
                tempShare.setSysUserId(user.getId());
                tempShareService.save(tempShare);
                // 修改分配次数
                user.setDayShareCount(user.getDayShareCount() + 1);
                userService.updateDayShareCount(user);
                // 分配记录
                ShareLog shareLog = new ShareLog();
                shareLog.setCustomerId(customer.getId());
                shareLogService.save(shareLog);
                // 扣款
                company.setBalance(company.getBalance().subtract(user.getMoney()));
                companyService.save(company);
                // 添加扣款日志
                AccountLog accountLog = new AccountLog();
                accountLog.setCompanyId(company.getId());
                accountLog.setCompanyName(company.getCompanyName());
                accountLog.setCustomerId(customer.getId());
                accountLog.setCustomerName(customer.getCusName());
                accountLog.setType("消费");
                accountLog.setAmount(user.getMoney());
                accountLog.setStartAmount(company.getBalance().add(user.getMoney()));
                accountLog.setEndAmount(company.getBalance());
                accountLog.setUserName(user.getName());
                accountLog.setUserId(user.getId());
                accountLog.setCreateTime(new Date());
                accountLogService.save(accountLog);
                customer.setStatus("1");
                customer.setInfo("分配成功！");
            } catch (Exception e) {
                customer.setStatus("-99");
                customer.setInfo(e.getMessage());
            }

        } else {
            customer.setStatus("-99");
            customer.setInfo("没找到分配用户！");
            mapper.update(customer);
        }
        if (mapper.update(customer) > 0 && "1".equals(customer.getStatus())) {
            // JdSmsClient.init();

            // 左心房 德驰2
             JSONObject jsonObject = ChuangLanSmsClient.sendSmsDeChi(user
             .getPhonenumber());
            SmsLog smsLog = new SmsLog();
            smsLog.setPhone(customer.getPhone());
            smsLog.setName(customer.getCusName());
            smsLog.setCompanyId(customer.getCompanyId());
            smsLog.setStatus(jsonObject.getString("code"));
            smsLog.setRemark("碟金/"+jsonObject.getString("msgId") + "/" + jsonObject.getString("errorMsg"));
            smsLogService.save(smsLog);
        }

    }

    @Override
    @Transactional(readOnly = false)
    public int shareCustomer(Customer customer, SysUser user) {
        int result = 0;
        if (null != user) {
            try {
                //  获取公司信息
                Company company = companyService.get(user.getCompanyId());
                // TODO  判断用户类型，如果是系统账号进行分配，如果不是系统账户则调用API推送信息
                if ("2".equals(user.getBusType())) {

                }
                if (user.getMoney().compareTo(company.getBalance()) > 0) {
                    return -1;
                }
                //开始分配
                customer = mapper.get(customer.getId());
                customer.setUserId(user.getUserId());
                customer.setUserName(user.getName());
                customer.setDeptId(user.getDeptId());
                customer.setDeptName(user.getDeptName());
                customer.setCompanyId(user.getCompanyId());
                customer.setShareDate(new Date());
                // 添加临时分配记录
                TempShare tempShare = new TempShare();
                tempShare.setSysUserId(user.getId());
                tempShareService.save(tempShare);
                // 修改分配次数
                user.setDayShareCount(user.getDayShareCount() + 1);
                userService.updateDayShareCount(user);
                // 分配记录
                ShareLog shareLog = new ShareLog();
                shareLog.setCustomerId(customer.getId());
                shareLogService.save(shareLog);
                // 扣款
                company.setBalance(company.getBalance().subtract(user.getMoney()));
                companyService.save(company);
                // 添加扣款日志
                AccountLog accountLog = new AccountLog();
                accountLog.setCompanyId(company.getId());
                accountLog.setCompanyName(company.getCompanyName());
                accountLog.setCustomerId(customer.getId());
                accountLog.setCustomerName(customer.getCusName());
                accountLog.setType("消费");
                accountLog.setAmount(user.getMoney());
                accountLog.setStartAmount(company.getBalance().add(user.getMoney()));
                accountLog.setEndAmount(company.getBalance());
                accountLog.setUserName(user.getName());
                accountLog.setUserId(user.getId());
                accountLog.setCreateTime(new Date());
                accountLogService.save(accountLog);
                customer.setStatus("1");

            } catch (Exception e) {
                customer.setStatus("-99");
                customer.setInfo(e.getMessage());
            }

        } else {
            customer.setStatus("-99");
            customer.setInfo("没找到分配用户！");

        }
        if (mapper.update(customer) > 0 && "1".equals(customer.getStatus())) {
            // 左心房 德驰2
            JSONObject jsonObject = ChuangLanSmsClient.sendSmsDeChi(user
                    .getPhonenumber());
            SmsLog smsLog = new SmsLog();
            smsLog.setPhone(customer.getPhone());
            smsLog.setName(customer.getCusName());
            smsLog.setCompanyId(customer.getCompanyId());
            smsLog.setStatus(jsonObject.getString("code"));
            smsLog.setRemark("碟金/"+jsonObject.getString("msgId") + "/" + jsonObject.getString("errorMsg"));
            smsLogService.save(smsLog);
            result = 1;
        }
        return result;
    }

    /**
     * 根据客户查询可分配的用户
     *
     * @param customer
     * @return
     */
    @Override
    public SysUser findNextShareUser(Customer customer) {
        Map<String, Object> params = new HashMap<>();
        if (StringUtils.isEmpty(customer.getCityName())) {
            return null;
        }
        String[] area = customer.getCityName().split("-");
        if (area.length == 2) {
            params.put("cityName", area[1]);
            params.put("type", customer.getType());
            List<SysUser> sysUserList = iSysUserService.findShareUser(params);
            if (null == sysUserList || sysUserList.size() == 0) {
                //没有可分配的用户了  表示一轮已经分完了
                SysUser sysUser=new SysUser();
                sysUser.setCity(area[1]);
                List<SysUser> shareUserList=iSysUserService.findList(sysUser);
                tempShareService.deleteAll(shareUserList);
                //重新查询
                sysUserList = iSysUserService.findShareUser(params);
            }
            //如果查询到用户列表取第一个用户 如果没有用户了，返回空用户
            return sysUserList.size() > 0 ? sysUserList.get(0) : null;
        }

        return null;

    }

    /**
     * 分配后修改状态
     *  废弃
     * @param customer
     */
    @Transactional(readOnly = false)
    @Override
    public void shareCustomerToSysUser(Customer customer) {
        shareCustomer(customer);
    }

    /**
     * @return 查询一个为分配的用户
     */

    @Override
    public Customer findOne() {
        return mapper.findOne();
    }

    @Transactional(readOnly = false)
    @Override
    public String importData(List<Customer> customers) {
        if (StringUtils.isNull(customers) || customers.size() == 0) {
            throw new CustomException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Customer customer : customers) {
            try {
                customer.setId(UUID.randomUUID().toString());
                customer.setStatus("0");
                customer.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
                customer.setIp(SecurityUtils.getLoginUser().getUser().getLoginIp());
                customer.setCreateTime(new Date());

                mapper.insert(customer);
                successNum++;
            } catch (Exception e) {
                failureNum++;
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，");
            throw new CustomException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，");
        }
        return successMsg.toString();
    }

    public static void main(String[] args) {
        System.out.println("四川-南通".indexOf("123"));
    }
}
